from datetime import datetime

from app.extentions import db
from app.models.commodity import Commodity
from app.models.cart import Cart


class Order(db.Model):
    __tablename__ = 'order'

    id = db.Column(db.Integer, primary_key=True)
    uid = db.Column(db.Integer, db.ForeignKey('user.id'))   # 用户id
    order_time = db.Column(db.DateTime, nullable=False)     # 下单时间
    commodity_list = db.Column(db.JSON)                     # 订单商品列表
    total_price = db.Column(db.Float, nullable=False)       # 订单总价

    def generate_by_pay(self, commodity_ids, uid):
        # 支付成功后，生成历史订单
        self.uid = uid
        self.order_time = datetime.now()
        self.commodity_list = []

        total_price = 0

        for commodity_id in commodity_ids:
            commodity = Commodity.query.get(commodity_id)
            cart_item = Cart.query.filter_by(commodity_id=commodity_id).first()

            # 计算某一商品的总价
            total_price += commodity.price * cart_item.commodity_count

            # 查询商品信息
            commodity_item = {
                "name": commodity.name,
                "price": commodity.price,
                "count": cart_item.commodity_count,
            }
            self.commodity_list.append(commodity_item)

        # 更新订单总价
        self.total_price = total_price

        db.session.add(self)
        db.session.commit()

    def serialize(self):
        return {
            'order_id': self.id,
            'order_time': str(self.order_time),
            'total_price': self.total_price,
            'commodity_list': self.commodity_list,
        }